import 'package:easy_chat_app/commons/GlobalStatus.dart';
import 'package:easy_chat_app/commons/db/repository/LocalConversationRepository.dart';
import 'package:easy_chat_app/commons/db/service/LocalConversationService.dart';
import 'package:easy_chat_app/commons/model/AppUserDetail.dart';
import 'package:easy_chat_app/commons/model/Conversation.dart';
import 'package:easy_chat_app/commons/model/GetUserChatGroupInfoListItem.dart';
import 'package:easy_chat_app/commons/utils/HttpUtils.dart';
import 'package:easy_chat_app/commons/utils/RouteUtils.dart';
import 'package:easy_chat_app/commons/widget/ChatGroupHeadPortrait.dart';
import 'package:easy_chat_app/mobile/page/MobileChatPage.dart';
import 'package:flutter/material.dart';
import 'package:logger/logger.dart';
import 'package:provider/provider.dart';
import 'package:sqflite/sqlite_api.dart';

import '../constants/MobileAppGlobalConstants.dart';

class MobileUserGroupListPageDataChangeNotifier extends ChangeNotifier {
  Logger logger = Logger();

  List<GetUserChatGroupInfoListResultData>
      getUserChatGroupInfoListResultDataList = [];

  Future<void> reload() async {
    getUserChatGroupInfoListResultDataList =
        (await HttpUtils.getUserChatGroupInfoList()).data ?? [];
    logger.i(
        "getUserChatGroupInfoListResultDataList:$getUserChatGroupInfoListResultDataList");
    notifyListeners();
  }
}

class MobileUserChatGroupListPage extends StatelessWidget {
  MobileUserChatGroupListPage({super.key});

  final Logger logger = Logger();

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (context) {
          var result = MobileUserGroupListPageDataChangeNotifier();
          result.reload();
          return result;
        })
      ],
      child: Consumer2<MobileUserGroupListPageDataChangeNotifier,
              AppUserDetailChangeNotifier>(
          builder: (context, mobileGroupListPageDataChangeNotifier,
              appUserDetailChangeNotifier, child) {
        List<GetUserChatGroupInfoListResultData> chatGroupInfoList =
            mobileGroupListPageDataChangeNotifier
                .getUserChatGroupInfoListResultDataList;
        AppUserDetail appUserDetail =
            appUserDetailChangeNotifier.getAppUserDetail();
        return Scaffold(
          appBar: AppBar(
            title: const Text("聊天群"),
            centerTitle: true,
            surfaceTintColor: MobileAppGlobalConstants.appBarSurfaceTintColor,
            backgroundColor: MobileAppGlobalConstants.appBarBackgroundColor,
          ),
          body: chatGroupList(chatGroupInfoList, appUserDetail,
              mobileGroupListPageDataChangeNotifier),
        );
      }),
    );
  }

  Widget chatGroupList(
      List<GetUserChatGroupInfoListResultData> chatGroupInfoList,
      AppUserDetail? appUserDetail,
      MobileUserGroupListPageDataChangeNotifier
          mobileGroupListPageDataChangeNotifier) {
    return ListView.builder(
        itemCount: chatGroupInfoList.length,
        itemBuilder: (context, index) {
          GetUserChatGroupInfoListResultData chatGroupInfo =
              chatGroupInfoList[index];
          List<UserHeadPortraitInfo> userHeadPortraitInfoList =
              (chatGroupInfo.chatGroupUserItemList ?? []).map((item) {
            return UserHeadPortraitInfo.create(
                item.code, item.headPortrait, item.headPortraitStoreType);
          }).toList();
          String chatGroupName = chatGroupInfo.name ??
              "群聊(${(chatGroupInfo.chatGroupUserItemList ?? []).length})";
          return GestureDetector(
            onTap: () async {
              await onTapChatGroupListItem(chatGroupInfo, appUserDetail,
                  mobileGroupListPageDataChangeNotifier);
            },
            child: Container(
              padding: const EdgeInsets.only(left: 15, right: 15),
              height: 55,
              child: Row(
                children: [
                  ChatGroupHeadPortrait.create(userHeadPortraitInfoList, 45),
                  const SizedBox(
                    width: 12,
                  ),
                  Expanded(
                      child: Container(
                    height: double.infinity,
                    alignment: Alignment.centerLeft,
                    decoration: const BoxDecoration(
                        border:
                            Border(bottom: BorderSide(color: Colors.black12))),
                    child: Text(
                      chatGroupName,
                      style: const TextStyle(
                          fontSize: 18,
                          color: Colors.black,
                          overflow: TextOverflow.ellipsis),
                    ),
                  ))
                ],
              ),
            ),
          );
        });
  }

  Future<void> onTapChatGroupListItem(
      GetUserChatGroupInfoListResultData chatGroupInfo,
      AppUserDetail? appUserDetail,
      MobileUserGroupListPageDataChangeNotifier
          mobileGroupListPageDataChangeNotifier) async {
    logger.i("onTapChatGroupListItem:$chatGroupInfo");
    Conversation conversation = (await HttpUtils.getOrCreateConversation(
            LocalConversationTypeConstants.group, null, chatGroupInfo.id))
        .data!;
    LocalConversation? localConversation =
        await LocalConversationService.getLocalConversationById(
            conversation.id!);
    if (localConversation == null) {
      localConversation = LocalConversation.create(
          id: conversation.id,
          uid1: conversation.uid1,
          uid2: conversation.uid2,
          chatGroupId: conversation.chatGroupId,
          type: conversation.type,
          updateTime: DateTime.now().millisecondsSinceEpoch,
          unreadMsgCount: 0);
      try {
        await LocalConversationService.addLocalConversation(localConversation);
      } on DatabaseException catch (ex) {
        logger.e(ex);
      }
    }

    await RouteUtils.route2MobileChatPage(MobileChatPageParams(
        currentUserId: appUserDetail?.id!,
        currentUserCode: appUserDetail?.code,
        currentUserNickName: appUserDetail?.nickname,
        currentUserHeadPortrait: appUserDetail?.headPortrait,
        currentUserHeadPortraitStoreType: appUserDetail?.headPortraitStoreType,
        localConversation: localConversation,
        chatGroupDetail: chatGroupInfo));
    await mobileGroupListPageDataChangeNotifier.reload();
  }
}
